<?php

namespace App\Http\Controllers\Admin;

use Admin;
use App\admin\src\Components\Callbacks\UpdateMenusCallback;
use App\Http\Controllers\Controller;
use App\Http\Requests\MenuRequest;
use App\Models\Menu;
use Illuminate\Http\Request;
use Largezhou\Admin\Form\Form;

class MenuController extends Controller
{
    public function index(Request $request)
    {
        $content = Admin::content()
                        ->title('菜单')
                        ->desc('所有菜单')
                        ->content($this->table());

        return response()->json([
            'status'  => true,
            'content' => $content,
        ]);
    }

    protected function table()
    {
        $table = Admin::table(Menu::class)
                      ->columns([
                          'id'           => '编号',
                          'parent.title' => '父级菜单',
                          'title'        => '标题',
                          'url'          => '地址',
                          'created_at'   => '添加时间',
                          'updated_at'   => '最后更新',
                      ]);

        return $table;
    }

    public function create(Request $request, Menu $menu)
    {
        $content = Admin::content()
                        ->title('菜单')
                        ->desc('添加菜单')
                        ->content($this->form($menu));

        return response()->json([
            'status'  => true,
            'content' => $content,
        ]);
    }

    public function edit(Request $request, Menu $menu)
    {
        $content = Admin::content()
                        ->title('菜单')
                        ->desc('编辑菜单')
                        ->content($this->form($menu)->edit());

        return response()->json([
            'status'  => true,
            'content' => $content,
        ]);
    }

    protected function form(Menu $menu = null)
    {
        $form = Admin::form($menu);

        $form->treeSelect('parent_id', '父级菜单')
             ->options(array_merge([
                 [
                     'value' => 0,
                     'label' => '顶级菜单',
                 ],
             ], Menu::makeTreeSelectOptions()))
             ->setDefault(0);

        $form->input('title', '标题')->required();
        $form->input('url', '地址');
        $form->input('icon', '图标')->setDefault('cogs');

        $form->complete(function (Form $form, $data) {
            $data['callback'] = new UpdateMenusCallback([
                'menus' => Menu::makeTreeOptions(),
            ]);

            return response()->json($data);
        });

        return $form;
    }

    public function store(MenuRequest $request, Menu $menu)
    {
        return $this->form($menu)->store();
    }

    public function destroy(Menu $menu)
    {
        return $this->form($menu)->destroy();
    }

    public function update(MenuRequest $request, Menu $menu)
    {
        return $this->form($menu)->update();
    }
}
